package com.mcc.websocket.service.impl;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.mcc.app.msg.service.IMsgRemindService;
import com.mcc.websocket.controller.WebSocketController;
import com.mcc.websocket.service.IWebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Iterator;

@Service
public class WebSocketServiceImpl implements IWebSocketService {

    @Autowired
    private IMsgRemindService msgRemindService;

    @Override
    public void sendMsgRemind(String operate) {
        try {
            JSONObject data = new JSONObject();
            data.set("count", msgRemindService.getMsgCount());
            data.set("operate", operate);

            JSONObject msg = new JSONObject();
            msg.set("event", "msgRemind");
            msg.set("data", data);

            Iterator<WebSocketController> it = WebSocketController.sessions.iterator();
            while (it.hasNext()) {
                WebSocketController webSocketController = it.next();
                Session session = webSocketController.getSession();
                synchronized (webSocketController) {
                    try {
                        session.getBasicRemote().sendText(msg.toString());
                    } catch (IllegalStateException | IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
